package com.caiyi.financial.nirvana.sms.service;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.base.service.BaseService;
import com.caiyi.financial.nirvana.sms.entity.SmsAuditBatch;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsAuditBatchStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.mapper.SmsAuditBatchMapper;
import com.caiyi.financial.nirvana.sms.querybean.PageBean;
import com.caiyi.financial.nirvana.sms.querybean.QueryBatchMsgBean;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.CoreSendUtil;
import com.caiyi.financial.nirvana.sms.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.youyu.common.api.Result;
import com.youyu.common.enums.BaseResultCode;
import com.youyu.common.exception.BizException;
import com.youyu.common.utils.YyAssert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class SmsAuditBatchService extends BaseService<SmsAuditBatch> {
    @Autowired
    private SmsAuditBatchMapper smsAuditBatchMapper;

    public PageBean<SmsAuditBatch> getBatchAuditByParams(QueryBatchMsgBean bean) {
        YyAssert.isFalse(null == bean.getStartTime(), ReturnCodeEnum.PARAMS_ERROR.code, "开始时间不能为空");
        if (null == bean.getEndTime()) {
            bean.setEndTime(new Date());
        }
        if (DateUtil.getDateDiffer(bean.getStartTime(), bean.getEndTime()) > 7) {
            YyAssert.isFalse(true, ReturnCodeEnum.PARAMS_ERROR.code, "开始时间和结束时间不能大于7天");
        }
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsAuditBatch> list = smsAuditBatchMapper.selectBatchMsgListByParams(bean);
        PageBean<SmsAuditBatch> pageBean = new PageBean<>(list);
        return pageBean;
    }


    public String updateBatchAuditByBatchId(String batchIds, Integer status, String auditAccount, String reason) {
        int count = 0;
        String[] batchIdList = batchIds.split(",");

        for (String batchId : batchIdList) {
            SmsAuditBatch smsBatchMsgAudit = smsAuditBatchMapper.selectAuditBybatchId(batchId);
            if (Objects.isNull(smsBatchMsgAudit)) {
                count++;
                continue;
            }
            String key = String.format(JedisKey.SMS_USER, smsBatchMsgAudit.getAccount());
            String userJson = JedisService.get(key);
            if (StringUtils.isBlank(userJson)) {
                YyAssert.isFalse(true, ReturnCodeEnum.ACCOUNT_ERROR.code, "账号不存在");
            }
            SmsUser user = JSON.parseObject(userJson, SmsUser.class);
            if (Objects.isNull(user)) {
                count++;
                continue;
            }
            int updateCount = smsAuditBatchMapper.updateBatchAuditByBatchId(batchId, status, auditAccount, reason, SmsAuditBatchStatusEnum.AUDIT.index);
            if (updateCount == 0) {
                count++;
                continue;
            }
            String content = smsBatchMsgAudit.getContent();
            Integer phoneCount = smsBatchMsgAudit.getPhoneCount();
            Integer msgCount = phoneCount * (CommUtil.splitLongContent(content).size());
            //返还余额
            String keyCount = String.format(JedisKey.SMS_BALANCE, smsBatchMsgAudit.getAccount());
            //设置为通过
            if (status == SmsAuditBatchStatusEnum.PASS.index) {
                SendQueueEntity entity = new SendQueueEntity();
                entity.setAccount(smsBatchMsgAudit.getAccount());
                entity.setContent(content);
                entity.setPhoneCount(phoneCount);
                entity.setPhone(smsBatchMsgAudit.getPhones());
                entity.setIp(smsBatchMsgAudit.getIp());
                entity.setNotifyUrl(smsBatchMsgAudit.getNotifyUrl());
                entity.setUid(smsBatchMsgAudit.getUid());
                entity.setProductId(user.getProductId());
                entity.setBatchId(batchId);
                Set<String> phones = new HashSet<>(Arrays.asList(smsBatchMsgAudit.getPhones().split(",")));
                try {
                    CoreSendUtil.handlerBusiness(phones, entity, user);
                } catch (Exception e) {
                    if (e instanceof BizException) {
                        if (((BizException) e).getCode().equals(ReturnCodeEnum.GATEWAY_CONFIG_ERROR.code) || ((BizException) e).getCode().equals(ReturnCodeEnum.PHONE_SIZE_ERROR.code)) {
                            smsAuditBatchMapper.updateBatchAuditByBatchId(batchId, SmsAuditBatchStatusEnum.AUDIT.index, auditAccount, reason, SmsAuditBatchStatusEnum.PASS.index);
                            //返还余额
                            JedisService.incrBy(keyCount, -msgCount);
                            JedisService.lpush(JedisKey.SMS_QUEUE_BALANCE_UPDATE, user.getId() + "=" + (-msgCount));
                        }
                    }
                    throw e;
                }
            }
            //审核驳回,返还余额
            if (status == SmsAuditBatchStatusEnum.REJECT.index) {
                //返还余额
                JedisService.incrBy(keyCount, msgCount);
                JedisService.lpush(JedisKey.SMS_QUEUE_BALANCE_UPDATE, user.getId() + "=" + (msgCount));
            }
        }
        return "成功条数：" + (batchIdList.length - count) + ",失败条数：" + count;
    }
}
